#!/bin/bash
# Benchmark a number of kernel builds
###SHELLPACK preamble kernbench 5.3
ITERATIONS=5
KERNBENCH_CONFIG=defconfig
KERNBENCH_TARGETS=vmlinux
KERNBENCH_SKIP_WARMUP=no

install-depends flex bison libelf-devel libopenssl-devel

###SHELLPACK parseargBegin
###SHELLPACK parseargInstall
###SHELLPACK parseargParam	--min-threads	KERNBENCH_MIN_THREADS
###SHELLPACK parseargParam	--max-threads	KERNBENCH_MAX_THREADS
###SHELLPACK parseargParam	--iterations	KERNBENCH_ITERATIONS
###SHELLPACK parseargParam	--kernel-config	KERNBENCH_CONFIG
###SHELLPACK parseargParam	--build-targets	KERNBENCH_TARGETS
###SHELLPACK parseargYes	--skip-warmup	KERNBENCH_SKIP_WARMUP
###SHELLPACK parseargEnd
###SHELLPACK monitor_hooks

KERNEL_FAMILY=v4.x
for V in `seq 2 5`; do
	echo $VERSION | grep -q ^$V
	if [ $? -eq 0 ]; then
		KERNEL_FAMILY=v$V.x
	fi
done

WEB_LOCATION=https://www.kernel.org/pub/linux/kernel/v5.x/linux-${VERSION}.tar.gz
MIRROR_LOCATION=$WEBROOT/kernbench/linux-$VERSION.tar.gz
THREADS=$(($NUMCPUS))
KERNBENCH_TARGETS=`echo $KERNBENCH_TARGETS | sed -e 's/,/ /g'`

###SHELLPACK init_only_start
	cd $SHELLPACK_DATA > /dev/null
	rm -f ./linux-$VERSION.tar.gz
	sources_fetch $WEB_LOCATION $MIRROR_LOCATION ./linux-$VERSION.tar.gz
	tar xf linux-$VERSION.tar.gz || die "Failed to extract"
	cd linux-$VERSION || die "Unexpected layout"

	# Configure
	yes '' | make $KERNBENCH_CONFIG > /dev/null 2>&1 || die "Failed to make $KERNBENCH_CONFIG"
	make -j$THREADS clean > /dev/null

	if [ "`uname -m`" = "aarch64" ]; then
		echo Removing broken entry from aarch64 $KERNBENCH_CONFIG
		sed -i -e '/CONFIG_CRYPTO_CRC32_ARM64/d' .config
		echo "# CONFIG_CRYPTO_CRC32_ARM64 is not set" >> .config
		yes '' | make oldconfig
	fi

	if [ "$KERNBENCH_SKIP_WARMUP" = "no" ]; then
		echo Install-only warming run
		make -j$THREADS $KERNBENCH_TARGETS > /dev/null 2>&1 || die "Failed to build $KERNBENCH_TARGETS"
	fi
	make clean >/dev/null
###SHELLPACK init_only_end

# Build pass
cd $SHELLPACK_DATA/linux-$VERSION || die "Unexpected layout"
###SHELLPACK threads_powertwo_begin $KERNBENCH_MIN_THREADS $KERNBENCH_MAX_THREADS $KERNBENCH_ITERATIONS
	monitor_pre_hook $LOGDIR_RESULTS $NR_THREADS
	###SHELLPACK iteration_begin $KERNBENCH_ITERATIONS
		echo Starting threads $NR_THREADS/$KERNBENCH_MAX_THREADS iteration $ITERATION/$KERNBENCH_ITERATIONS
		sync

		save_rc $TIME_CMD make -j$NR_THREADS $KERNBENCH_TARGETS 2>> $LOGDIR_RESULTS/kernbench-${NR_THREADS}-$ITERATION.time > /dev/null
		grep elapsed $LOGDIR_RESULTS/kernbench-${NR_THREADS}-$ITERATION.time``
		recover_rc
		if [ $? -ne 0 ]; then
			die Failed to run kernbench
		fi

		# cleanup
		make clean >/dev/null
	###SHELLPACK iteration_end $ITERATIONS
	monitor_post_hook $LOGDIR_RESULTS $NR_THREADS
###SHELLPACK threads_powertwo_end

# Cleanup
rm -rf $SHELLPACK_DATA/*

# clean up the tree to save space
popd > /dev/null
rm -rf $TMPDIR/kernbench

exit $SHELLPACK_SUCCESS
